package com.cloud.dict.service.impl;

import com.cloud.dict.entity.DictionaryGroup;
import com.cloud.dict.entity.DictionaryValue;
import com.cloud.dict.service.DictionaryService;
import com.cloud.dict.web.query.DictionaryGroupResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class DictionaryServcieImpl implements DictionaryService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<DictionaryGroupResponse> findGroupList() {
        List<DictionaryGroup> dictionaryGroups = new DictionaryGroup().selectAll();
        List<DictionaryGroupResponse> collect = dictionaryGroups.stream().map(e -> {
            DictionaryGroupResponse dictionaryGroupResponse = new DictionaryGroupResponse();
            BeanUtils.copyProperties(e, dictionaryGroupResponse);
            return dictionaryGroupResponse;
        }).collect(Collectors.toList());
        return collect;
    }

//    @Override
//    public void refreshCache() {
//        List<DictionaryGroup> dictionaryGroups = new DictionaryGroup().selectAll();
//        Map<Long, DictionaryGroup> collect = dictionaryGroups.stream().collect(Collectors.toMap(DictionaryGroup::getId, Function.identity()));
//        List<DictionaryValue> dictionaryValues = new DictionaryValue().selectAll();
//        dictionaryValues.stream().forEach(e->{
//            DictionaryGroup dictionaryGroup = collect.get(e.getGroupId());
//            redisTemplate.opsForValue().set(dictionaryGroup.getGroupName()+"_"+e.getDictionaryKey(),e.getDictionaryValue());
//        });
//    }
    @Override
    public void refreshCache() {
        List<DictionaryGroup> dictionaryGroups = new DictionaryGroup().selectAll();
        List<DictionaryValue> dictionaryValues = new DictionaryValue().selectAll();
        Map<Long, List<DictionaryValue>> dictionaryValuesMap = dictionaryValues.stream().collect(Collectors.groupingBy(DictionaryValue::getGroupId));
        dictionaryGroups.stream().forEach(e->{
            List<DictionaryValue> dictionaryValues1 = dictionaryValuesMap.get(e.getId());
            HashMap<String, String> map = new HashMap<>();
            dictionaryValues1.stream().forEach(m->{
                map.put(m.getDictionaryKey(),m.getDictionaryValue());
            });
            redisTemplate.opsForHash().putAll(e.getGroupValue(),map);
        });
    }


}
